<?php
namespace shopend\controllers;

use common\models\Service;
use common\service\ConstantService;
use common\models\Shop;
use common\models\Withdraw;
use common\service\WechatService;
use common\service\GlobalUrlService;
use common\service\CommonService;
use common\models\Code;
use common\models\MoneyChange;
use common\models\Googs;
use common\models\Tree;
class WithdrawController extends BaseController
{


    /**
     * 获取商家信息
     */
    public function actionGetshop(){
        $mo = Shop::find()->where(['id'=>$this->shop['id']])->asArray()->one();
        $mo['service_rate'] = $mo['service_rate']?$mo['service_rate']:ConstantService::$service_rate;
        $mo['phone'] = $mo['admin_phone'];
        $mo['admin_phone'] = substr_replace($mo['admin_phone'],'****',3,4);
        $mo['money'] = sprintf("%.2f",$mo['shop_money']);
        $mo['order_money'] = sprintf("%.2f",$mo['shop_money']-$mo['service_money']);
        $count = Withdraw::find()->select('count(*) as count')->where(['shop_id'=>$this->shop['id']])->asArray()->one();
        $mo['counts'] = $count['count'].'笔';
        $mo['yhk_list'] = ConstantService::$bank_code;
        $mo['sum'] = $this->GetWithdrawMoney();
        if($mo){
            return $this->renderJson($mo,'',ConstantService::$response_success);
        }
    }

    public function actionIndex(){
        return $this->render('index', ['data' => '']);
    }

    /**
     * 提现列表
     * @return string
     */
    public function actionIndexList(){
        $Withdraw = Withdraw::find();
        $Withdraw->andWhere(['shop_id'=>$this->shop['id']]);
        $p = intval( $this->get('p',1) );
        $p = ( $p > 0 )? $p : 1;
        $pages = CommonService::ipagination( [
            'total_count' => $Withdraw->count(),//总条数
            'page_size' => $this->get('limit',10),
            'page' => $p,
            'display' => 10
        ]);
        $offset = ($p - 1) * $this->get('limit',10);
        $data = $Withdraw->select('id,withdraw_money,withdraw_no,create_time,withdraw_status')
            ->limit($this->get('limit',10))
            ->offset($offset)
            ->orderBy(['id'=>SORT_DESC])
            ->asArray()
            ->all();
        return $this->render('index-list',[
            'data' => $data,
            'pages' => $pages,
            'url' => '/withdraw/index-list',
            'search_conditions' => ['title'=>'提现申请']]);
    }

    /**
     * 服务费列表
     * @return string
     */
    public function actionServiceList(){
        $Service = Service::find();
        $Service->andWhere(['shop_id'=>$this->shop['id']]);
        $p = intval( $this->get('p',1) );
        $p = ( $p > 0 )? $p : 1;
        $pages = CommonService::ipagination( [
            'total_count' => $Service->count(),//总条数
            'page_size' => $this->get('limit',10),
            'page' => $p,
            'display' => 10
        ]);
        $offset = ($p - 1) * $this->get('limit',10);
        $data = $Service->select('id,order_id,order_money,service_money,create_time')
            ->limit($this->get('limit',10))
            ->offset($offset)
            ->orderBy(['id'=>SORT_DESC])
            ->asArray()
            ->all();
        return $this->render('service-list',[
            'data' => $data,
            'pages' => $pages,
            'url' => '/withdraw/service-list',
            'search_conditions' => ['title'=>'服务费明细']
        ]);
    }

    /**
     * 验证密码
     */
    public function actionCheckpwd(){
        $pwd = $this->post('pwd');
        if(empty($pwd)){
            return $this->renderJson([],'密码不能为空',ConstantService::$response_fail);
        }
        $pwd = md5(md5($pwd).$this->salt);

        $mo = Shop::find()->select('withdraw_pwd,id')->where(['id'=>$this->shop['id']])->asArray()->one();
        if($pwd == $mo['withdraw_pwd']){
            return $this->renderJson(1,'',ConstantService::$response_success);
        }
        return $this->renderJson($mo,'密码错误',ConstantService::$response_fail);
    }


    /**
     * 修改提款密码
     */
    public function actionUpdateWithdrawPwd()
    {
        $code = $this->post('yzm');
        $this->_checkcode($code);
        $pwd = $this->post('pwd');
        $reppwd = $this->post('reppwd');
        if ($reppwd != $pwd) {
            return $this->renderJson([], '重复密码不一样', ConstantService::$response_fail);
        }

        $data = Shop::findOne(['id' => $this->shop['id']]);

        $data->withdraw_pwd = md5(md5($pwd) . $this->salt);
        if ($data->save()) {
            return $this->renderJson([], '操作成功', ConstantService::$response_success);
        }
        return $this->renderJson([],'密码修改失败',ConstantService::$response_fail);
    }
    /**
     * 获取上一条银行卡
     */
    public function actionGetWithdrawInfo(){
        $lastinfo = Withdraw::find()
            ->where(['shop_id'=>$this->shop['id'],'type'=>1])
            ->orderBy(['create_time'=>SORT_DESC])
            ->limit(1)
            ->one();
        if($lastinfo){
            return $this->renderJson($lastinfo,'',ConstantService::$response_success);
        }
        $lastinfo = [
            'shop_id' => 0,
            'bank_name' => '',
            'bank_code' => 0,
            'bank_no' => '',
        ];
        return $this->renderJson($lastinfo,'',ConstantService::$response_success);
    }


    /**
     * 提交提现申请
     */
    public function actionAddWihdraw(){
        $data = $this->post();
        $moneys = $this->post('withdraw_money');
        $summoney = $this->GetWithdrawMoney();

        $shops = Shop::find()
            ->select('shop_money,service_money,service_rate')
            ->andWhere(['id'=>$this->shop['id']])
            ->asArray()
            ->one();
        $sxf = 1;
        if($moneys > 1000){
            $sxf = sprintf("%.2f",$moneys*0.001 );
        } elseif($moneys >= 25000) {
            $sxf = 25;
        }
        $service_rate = !empty($shops['service_rate']) ?$shops['service_rate'] :ConstantService::$service_rate;

        $sxf = sprintf("%.2f",$sxf + $moneys * ($service_rate / 100) );

        if($moneys > $shops['shop_money']){
            return $this->renderJson([],'帐户余额不足',ConstantService::$response_fail);
        }
        if(($summoney + $moneys) > 50000){
            return $this->renderJson([],'您已超过当天提现限额,每天限额提现5W',ConstantService::$response_fail);
        }
        $moneyData = MoneyChange::find()
            ->where(['shop_id'=>$this->shop['id']])
            ->orderBy(['create_time'=>SORT_DESC])
            ->asArray()
            ->one();

        $bmoney = $moneyData['after_money']?$moneyData['after_money']:$this->shop['shop_money'];
        $amoney = $moneyData['after_money']?sprintf("%.2f",$moneyData['after_money'] - $this->post('withdraw_money')):sprintf("%.2f",$this->shop['shop_money']-$this->post('withdraw_money'));
        $withdrawData['before_money'] = (float)$bmoney;
        $withdrawData['after_money'] = (float)$amoney;
        $withdrawData['shop_service_money'] = $shops['service_money'];
        $withdrawData['service_rate'] = $shops['service_rate'];
        $withdrawData['shop_id'] = $this->shop['id'];
        $withdrawData['shop_name'] = $this->shop['shop_name'];
        $withdrawData['shop_phone'] = $this->shop['admin_phone'];
        $withdrawData['withdraw_money'] = $moneys;
        $withdrawData['withdraw_no'] =  CommonService::createOrderNo();
        $withdrawData['service_money'] = 0;
        $withdrawData['withdraw_status'] = 0;
        $withdrawData['type'] = $data['type'];
        $withdrawData['openid'] = $this->shop['openid'];
        $withdrawData['create_time'] = time();

        $moneychangeData['money'] = $this->post('withdraw_money');

        if($data['type'] == 1){ //银行卡提现
            $msg = $this->_checkcode($data['yzm']);
            if($msg !== true){
                return $this->renderJson([],$msg,ConstantService::$response_fail);
            }
            $moneychangeData['money'] = $moneys;
            $amoney = $amoney-$shops['service_money'];
            $withdrawData['after_money'] = (float)$amoney;
            $withdrawData['bank_code'] = $data['khh'];
            $withdrawData['bank_no'] = $data['zzyhk'];
            $withdrawData['user_name'] = $data['khr'];
            $withdrawData['service_money'] = $sxf;
            foreach (ConstantService::$bank_code as $key=>$val){
                if($key == $data['khh']){
                    $withdrawData['bank_name'] = $val;
                }
            }
        }

        $sxmoney = $amoney-$sxf;
        $moneychangeDb = new MoneyChange();
        $moneychangeData['after_money'] = (float)$sxmoney;
        $moneychangeData['before_money'] = (float)$bmoney;
        $moneychangeData['shop_id'] = $this->shop['id'];
        $moneychangeData['remark'] = '商家提现';
        $moneychangeData['type'] = 1;
        $moneychangeData['create_time'] = time();
        $withdrawDb = new withdraw();
        $withdrawDb->setAttributes($withdrawData);
        if($withdrawDb->save()){
            $moneychangeDb->setAttributes($moneychangeData);
            if($moneychangeDb->save()) {

                $shopData = shop::findOne(['id'=>$this->shop['id']]);
                $shopData->shop_money = $amoney;
                $shopData->service_money = 0;
                if($shopData->save()){
                    $count = Withdraw::find()->select('count(*) as count')->where(['shop_id'=>$this->shop['id']])->asArray()->one();
                    return $this->renderJson(['money'=>sprintf("%.2f",$amoney),'order_money' => 0,'count'=>$count['count'].'笔'], '操作成功', ConstantService::$response_success);
                }
            }
        }
        return $this->renderJson([],'操作失败',ConstantService::$response_fail);
    }



    /**
     * 验证验证码是否正确
     * @param $phone
     * @param $code
     * @return string
     */
    private function _checkcode($code){

        if(empty($code)){
            return '验证码不能为空';
        }
        $data = Code::find()->where(['phone'=>$this->shop['admin_phone']])->orderBy(['id'=>SORT_DESC])->asArray()->one();

        if((time()-$data['time'])>300 || $data['is_del'] == 1){
            return '验证码错误';
        }

        if($data['code'] == $code){
            $Codes = Code::findOne(['id'=>$data['id']]);
            $Codes->is_del = 1;
            $Codes->save();
            return true;
        }

        return '验证码错误';
    }

    /**
     * 查看详情
     * @return string
     */
    public function actionInfo(){
        $id = $this->get('id');
        $row = Withdraw::find()->where(['id'=>$id])->asArray()->one();
        return $this->render('info',['row'=>$row]);
    }

    /**
     * 查询每天提现金额
     * @return string
     */
    private function GetWithdrawMoney(){
        $beg = strtotime(date('Y-m-d'));
        $end = strtotime(date('Y-m-d',strtotime('+1 day')));
        $money = Withdraw::find()
            ->select("sum(withdraw_money) as withdraw_money ,sum(service_money) as service_money")
            ->andWhere(['shop_id'=>$this->shop['id']])
            ->andWhere(['>=','create_time',$beg])
            ->andWhere(['<=','create_time',$end])
            ->asArray()
            ->one();
        $sum = sprintf("%.2f",$money['withdraw_money']+$money['service_money']);
        return $sum;
    }
}